import axios from 'axios'
import router from '../router'
import qs from 'qs'
import { Message,Loading } from 'element-ui'
import { getToken,removeToken,getInstId } from './permission'

let loading; // 声明变量

// 请求地址
if (process.env.NODE_ENV == 'development') {
	axios.defaults.baseURL = process.env.BASE_API;
} else if (process.env.NODE_ENV == 'debug') {
	axios.defaults.baseURL = '';
} else if (process.env.NODE_ENV == 'production') {
	axios.defaults.baseURL = process.env.BASE_API;
};

// 请求超时时间
axios.defaults.timeout = 30000;

// 请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 请求拦截器
axios.interceptors.request.use(config => {
	loading = Loading.service({
		lock: true,
		background: "rgba(0, 0, 0, 0)"
	})
	if (getToken()) {
		config.headers['Authorization'] = getToken();
		if (config.method === "post") {
			let data = qs.parse(config.data);
			config.data = qs.stringify({
				inst_id: getInstId(),
				...data
			});
		}else if (config.method === "get") {
			config.params = {
				inst_id: getInstId(),
				...config.params
			}
		}
	}
	return config;
}, error => {
	loading.close();
	return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(
response => {
	loading.close();
	if(response.data && response.data.code == 501){
		let options = {
			message: '很抱歉，登录时效已过期，请重新登录。',
			type: 'error',
			duration: 800,
			onClose: function(){
				removeToken();
				router.replace(
					{ path: '/login' }, 
					onComplete => {}, onAbort => {}
				)
			}
		}
		Message(options);
	}
	return response;
}, error => {
	loading.close();
	if (error && error.response) {
		switch (error.response.status) {
			case 501:
				removeToken();
				router.replace(
					{ path: '/login' }, 
					onComplete => {}, onAbort => {}
				)
			case 404:
				error.message = '请求错误,未找到该资源'
				break;
			default:
				error.message = `连接错误${error.response.status}`
		}
	}
	Message.error(error.message)
	return Promise.reject(error.response.data);
})

/** 
 * get方法，对应get请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function get(url, params){    
    return new Promise((resolve, reject) =>{        
        axios.get(url, {            
            params: params
        })        
        .then(res => {            
            resolve(res.data);        
        })        
        .catch(err => {            
            reject(err.data)        
        })    
    });
}

/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function post(url, params) {    
    return new Promise((resolve, reject) => {         
        axios.post(url, qs.stringify(params))
        .then(res => {            
            resolve(res.data);        
        })        
        .catch(err => {            
            reject(err.data)        
        })    
    });
}
